Defining a Base Class
- Any class that does not inherit from another class is known as a base class.
- Swift classes do not inherit from a universal base class. Classes you define without specifying a superclass automatically become base classes for you to build upon.
1 | class Vehicle { |
Subclassing
Subclassing is the act of basing a new class on an existing class. The subclass inherits characteristics from the existing class, which you can then refine. You can also add new characteristics to the subclass.
1 | class SomeSubclass: SomeSuperclass { |
Overriding
A subclass can provide its own custom implementation
Accessing Superclass Methods, Properties, and Subscripts
- calling
super.someMethod()
within the overriding method implementation. super.someProperty
within the overriding getter or setter implementation.super[someIndex]
from within the overriding subscript implementation.
Overriding Methods
1 | class Train: Vehicle { |
Overriding Properties
- provide your own custom getter and setter for that property
- add property observers to enable the overriding property
Overriding Property Getters and Setters
property | Custom Getter | Custom Setter |
---|---|---|
Inherited stored | yes | yes |
Inherited computed | yes | yes |
- custom getter (and setter,) to override any inherited property( stored or computed property.
- subclass only know inherited property has a certain name and type.
- Must state name and type in subclass to check .
- You can present an inherited read-only property as a read-write property by providing both a getter and a setter in your subclass property override. You cannot, however, present an inherited read-write property as a read-only property.
- If you have setter for override , then you must have getter for it.
1 | class Car: Vehicle { |
Overriding Property Observers
- add property observers to an inherited property. This enables you to be notified when the value of an inherited property changes
- You cannot add property observers to inherited constant stored properties or inherited read-only computed properties.
- Note also that you cannot provide both an overriding setter and an overriding property observer for the same property. If you want to observe changes to a property’s value, and you are already providing a custom setter for that property, you can simply observe any value changes from within the custom setter.
1 | class AutomaticCar: Car { |
Preventing Overrides
final var
,final func
,final class func
, andfinal subscript
- Methods, properties, or subscripts that you add to a class in an extension can also be marked as final within the extension’s definition.
- You can mark an entire class as final by writing the final modifier before the class keyword in its class definition (
final class
).